package com.xjoyt.pay.share.services;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyun.oss.OSSClient;
import com.xjoyt.pay.abstracts.AbstractService;
import com.xjoyt.pay.api.ali.OssUtils;
import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.dto.PageParam;
import com.xjoyt.pay.dto.PageResult;
import com.xjoyt.pay.share.params.BucketPageParam;
import com.xjoyt.pay.share.po.Bucket;
import com.xjoyt.pay.share.repository.BucketRepository;

@Service
public class BucketService extends AbstractService {

	@Autowired
	private BucketRepository repository;

	public Bucket get(String id) {
		return repository.findOne(id);
	}

	public PageResult<Bucket> loadPage(PageParam<BucketPageParam> param) {
		return repository.loadPage(param);
	}

	public ExecuteResult<?> delete(String id) {
		repository.delete(id);
		return ExecuteResult.ok();
	}

	public ExecuteResult<Bucket> save(Bucket param) {
		if ((StringUtils.isBlank(param.id)
				&& repository.findOneByEndpointAndAccessKeyAndSecretKeyAndName(param.endpoint, param.accessKey,
						param.secretKey, param.name) != null)
				|| (StringUtils.isNotBlank(param.id)
						&& repository.findOneByIdNotAndEndpointAndAccessKeyAndSecretKeyAndName(param.id, param.endpoint,
								param.accessKey, param.secretKey, param.name) != null)) {
			return ExecuteResult.fail("该云存储已存在");
		}

		try {
			OSSClient client = OssUtils.getClient(param.endpoint, param.accessKey, param.secretKey);
			client.getBucketInfo(param.name);
		} catch (Exception e) {
			e.printStackTrace();
			return ExecuteResult.fail("信息错误");
		}

		if (param.addedDate == null) {
			param.addedDate = new Date();
		}
		Bucket entity = repository.save(param);
		return ExecuteResult.ok(entity);
	}

	public ExecuteResult<?> setDefault(String id) {
		Bucket entity = repository.findOne(id);
		if (entity == null) {
			ExecuteResult.fail("数据不存在");
		}

		repository.findAll().forEach(item -> {
			item.defaultBucket = false;
			repository.save(item);
		});

		entity.defaultBucket = true;
		repository.save(entity);
		return ExecuteResult.ok("设置成功");
	}

	public Bucket getDefault() {
		return repository.findOneByEnabledTrueAndDefaultBucketTrue();
	}
}
